const query = require("../db/mysql")
const { success, error } = require("../module/module")

class Audit {
    //搜索
    searchVal = async (ctx) => {
        let { keyword } = ctx.request.body
        let sql = `select * from audit where 1=1 `
        if (keyword) {
            sql += `and Villagename like "%${keyword}%"`
        }
        let data = await query(sql)
        ctx.body = success(data, '查找成功')
    }
    //数据分页
    getData = async (ctx) => {
        let { pageIndex, pageSize } = ctx.query
        let sql = `select * from audit where 1=1 `
        let countSql = 'select count(id) as total from audit '
        let total = await query(countSql)
        if (pageIndex && pageSize) {
            sql += `limit ${(pageIndex * 1 - 1) * pageSize * 1},${pageSize * 1} `
        }
        let data = await query(sql)
        ctx.body = {
            data,
            code: 1,
            total: total[0].total
        }
    }
    //审核
    audit = async (ctx) => {
        let { id, keyword } = ctx.request.body
        let sql = `select * from audit where id=${id} `
        let item = await query(sql)
        if (item[0].state === '待审核') {
            let change = `update audit set state="已审核" where id=${id} `
            let data = await query(change)
            if (data.affectedRows === 1) {
                ctx.body = success(data, '已审核')
            }

        } else {
            let shenOk = `update audit set state="待审核" where id=${id} `
            let data = await query(shenOk)
            if (data.affectedRows === 1) {
                ctx.body = success(data, '待审核')
            }
        }
    }
    //编辑回显
    backLook = async (ctx) => {
        let { id } = ctx.request.body
        let sql = `select * from audit where id=${id} `
        let data = await query(sql)
        if (data.length) {
            ctx.body = success(data)
        }

    }
    //编辑
    handleEdit = async (ctx) => {
        let { id, Villagename, title, area, price, sort, state } = ctx.request.body
        let sql = `update audit set Villagename="${Villagename}", title="${title}", area="${area}", price="${price}", sort="${sort}", state="${state}"  where id=${id} `
        let data = await query(sql)
        if (data.affectedRows === 1) {
            ctx.body = success(data, '编辑成功')
        } else {
            ctx.body = error('编辑失败')
        }

    }
    //删除
    handleDelete = async (ctx) => {
        let { id } = ctx.request.body
        let sql = `delete from audit where id=${id} `
        let data = await query(sql)
        if (data.affectedRows === 1) {
            ctx.body = success(data, '删除成功')
        } else {
            ctx.body = error('不存在此条信息')
        }
    }
}

module.exports = new Audit()